from sqlalchemy import and_, or_, func
from datetime import datetime, timedelta
from app import db
from app.models.user import User
from app.models.user_profile import UserProfile
from app.models.user_photo import UserPhoto
from app.models.mate_criteria import MateCriteria


class UserReviewService:
    """用户审核服务层"""
    
    @staticmethod
    def get_pending_users(page=1, per_page=20, keyword=''):
        """
        获取待审核用户列表
        
        Args:
            page: 页码
            per_page: 每页数量
            keyword: 搜索关键词
            
        Returns:
            tuple: (用户列表, 总数)
        """
        query = User.query.filter(User.status == 2)  # 待审核状态
        
        # 搜索过滤
        if keyword:
            query = query.filter(or_(
                User.nickname.like(f'%{keyword}%'),
                User.phone.like(f'%{keyword}%'),
                User.real_name.like(f'%{keyword}%')
            ))
        
        # 按创建时间倒序
        query = query.order_by(User.created_at.desc())
        
        # 分页查询
        users = query.offset((page - 1) * per_page).limit(per_page).all()
        total = query.count()
        
        return users, total
    
    @staticmethod
    def review_user(user_id, status, reason='', admin_id=None):
        """
        审核用户
        
        Args:
            user_id: 用户ID
            status: 审核结果 1通过 3不通过
            reason: 审核不通过原因
            admin_id: 审核管理员ID
            
        Returns:
            dict: 审核后的用户信息
        """
        user = User.query.get(user_id)
        if not user:
            return None
        
        # 只有待审核状态的用户才能被审核
        if user.status != 2:
            raise Exception("该用户不是待审核状态")
        
        # 更新用户状态
        user.status = status
        
        # 记录审核信息（可以后续扩展为审核记录表）
        user.updated_at = datetime.now()
        
        # 如果审核不通过，可以在用户表中添加备注字段存储原因
        # 这里暂时通过异常或其他方式处理
        
        db.session.commit()
        
        return user.to_dict()
    
    @staticmethod
    def batch_review_users(user_ids, status, reason='', admin_id=None):
        """
        批量审核用户
        
        Args:
            user_ids: 用户ID列表
            status: 审核结果 1通过 3不通过
            reason: 审核不通过原因
            admin_id: 审核管理员ID
            
        Returns:
            tuple: (成功数量, 失败数量)
        """
        success_count = 0
        failed_count = 0
        
        for user_id in user_ids:
            try:
                result = UserReviewService.review_user(user_id, status, reason, admin_id)
                if result:
                    success_count += 1
                else:
                    failed_count += 1
            except Exception:
                failed_count += 1
        
        return success_count, failed_count
    
    @staticmethod
    def get_user_review_detail(user_id):
        """
        获取用户审核详情
        
        Args:
            user_id: 用户ID
            
        Returns:
            dict: 用户详细信息
        """
        user = User.query.get(user_id)
        if not user:
            return None
        
        # 基本用户信息
        user_data = user.to_dict()
        
        # 添加详细资料
        if user.profile:
            user_data['profile'] = user.profile.to_dict()
        
        # 添加照片信息
        photos = UserPhoto.query.filter_by(user_id=user_id).order_by(UserPhoto.sort_order.asc()).all()
        user_data['photos'] = [photo.to_dict() for photo in photos]
        
        # 添加择偶条件
        mate_criteria = MateCriteria.query.filter_by(user_id=user_id).first()
        if mate_criteria:
            user_data['mate_criteria'] = mate_criteria.to_dict()
        
        # 计算资料完整度
        user_data['completeness'] = user.get_profile_completeness()
        
        # 添加审核建议
        user_data['review_suggestions'] = UserReviewService._get_review_suggestions(user)
        
        return user_data
    
    @staticmethod
    def _get_review_suggestions(user):
        """
        获取审核建议
        
        Args:
            user: 用户对象
            
        Returns:
            list: 审核建议列表
        """
        suggestions = []
        
        # 检查基本信息完整性
        if not user.nickname or len(user.nickname) < 2:
            suggestions.append("昵称不完整或过短")
        
        if not user.birthday:
            suggestions.append("未填写生日")
        
        if not user.height or user.height < 140 or user.height > 220:
            suggestions.append("身高信息异常")
        
        if not user.city:
            suggestions.append("未填写所在城市")
        
        # 检查照片
        photo_count = UserPhoto.query.filter_by(user_id=user.id).count()
        if photo_count == 0:
            suggestions.append("未上传任何照片")
        elif photo_count < 3:
            suggestions.append("照片数量较少，建议至少3张")
        
        if not user.avatar:
            suggestions.append("未设置头像")
        
        # 检查资料完整度
        completeness = user.get_profile_completeness()
        if completeness < 60:
            suggestions.append(f"资料完整度较低：{completeness}%")
        
        # 检查详细资料
        if user.profile:
            if not user.profile.education:
                suggestions.append("未填写学历信息")
            if not user.profile.occupation:
                suggestions.append("未填写职业信息")
            if not user.profile.self_intro or len(user.profile.self_intro) < 20:
                suggestions.append("自我介绍过于简单")
        else:
            suggestions.append("未填写详细资料")
        
        # 检查择偶条件
        mate_criteria = MateCriteria.query.filter_by(user_id=user.id).first()
        if not mate_criteria:
            suggestions.append("未设置择偶条件")
        
        if not suggestions:
            suggestions.append("资料完整，建议通过审核")
        
        return suggestions
    
    @staticmethod
    def get_review_statistics():
        """
        获取审核统计数据
        
        Returns:
            dict: 统计数据
        """
        # 总用户数
        total_users = User.query.count()
        
        # 各状态用户数
        pending_count = User.query.filter(User.status == 2).count()
        approved_count = User.query.filter(User.status == 1).count()
        rejected_count = User.query.filter(User.status == 3).count()
        
        # 今日新增用户
        today = datetime.now().date()
        today_new = User.query.filter(func.date(User.created_at) == today).count()
        
        # 今日待审核用户
        today_pending = User.query.filter(
            and_(
                User.status == 2,
                func.date(User.created_at) == today
            )
        ).count()
        
        # 本周统计
        week_ago = datetime.now() - timedelta(days=7)
        week_new = User.query.filter(User.created_at >= week_ago).count()
        week_approved = User.query.filter(
            and_(
                User.status == 1,
                User.updated_at >= week_ago
            )
        ).count()
        
        return {
            'total_users': total_users,
            'pending_count': pending_count,
            'approved_count': approved_count,
            'rejected_count': rejected_count,
            'today_new': today_new,
            'today_pending': today_pending,
            'week_new': week_new,
            'week_approved': week_approved,
            'approval_rate': round((approved_count / max(total_users, 1)) * 100, 2)
        } 